package com.yorge.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class RabbitMQReceive {

    @Autowired
    RedisTemplate<String, String> redisTemplate;

/*    @RabbitHandler
    @RabbitListener(queues = {"yorge","yorge1","yorge2","yorge3"}) //监听队列名为hello的队列
    public void receiveDirectMsg(String msg) {
        log.info("监听器接收到的消息：{} ", msg);

        // 如果是convertAndSend方法发送过来的消息，不能有return 反参
        // 如果是convertSendAndReceive方法发过来的消息，会灵活一些, 没有反参会默认是空
//        return "发送成功！msg=" + msg;
    }*/

    @RabbitHandler
    @RabbitListener(queues = {"yorge","yorge1","yorge2","yorge3"}) //监听队列名为hello的队列
    public String receiveDirectMsg(Message message) {
        log.info("监听器接收到的消息：{} ", message);

        MessageProperties messageProperties = message.getMessageProperties();
        String messageId = messageProperties.getMessageId();

        Boolean aBoolean = redisTemplate.hasKey(messageId);
        if (aBoolean) {
            return "已接受过该消息，拒绝重复消费！";
        } else {
            redisTemplate.opsForValue().set(messageId, "");
            redisTemplate.expire(messageId, 100, TimeUnit.SECONDS);

            String msg = new String(message.getBody(), StandardCharsets.UTF_8);
            return "发送成功！msg=" + msg;
        }
    }

}
